package locationServices;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import General.GlobalValueClass;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;


public class GetGpsCoordinate extends AsyncTask<String, String, String>{

	private FileOutputStream out;


	private File FileToSave;
	private String [] Progress;
	private Calendar calendar;
	
	StringBuilder sb1 = new StringBuilder();  
	
	private LocationManager mlocManager = null;
	private LocationListener mlocListener = null;
	private Context UIThread = null;
	
	private double longitude;
	private double latitude;
	private double altitude;
	private double speed;
	private File root;
	private File dir1;
	
	private int sleepTime;
	
	private boolean GEttingCoordinates = true;
	
	//Constructor
	public GetGpsCoordinate(){

		//CREATES A DIRECTORY ON THE SDCARD IF IT ALREADY EXISTS, CREATES A FILE THAT COMES BY ARGUMENT
		root = android.os.Environment.getExternalStorageDirectory();
		dir1 = new File (root.getAbsolutePath()+ "/TrackingData"); //creates directory
        
        mlocManager = GlobalValueClass.GET_mlocManager();
        mlocListener = GlobalValueClass.GET_mlocListener(); 
        Progress = new String[1];
        Progress[0] = new String();
        UIThread = GlobalValueClass.GET_Context();
        sleepTime = GlobalValueClass.GET_Frequency();  
        
        
        execute();
	}
	
	@Override
	protected String doInBackground(String... arg0) { //first string is the name of the CSV file where the coordinates shall be put

		
    	
		if(root.canWrite())
        {
	        if(!dir1.exists())
	        {
	            dir1.mkdirs();
	            FileToSave = new File(dir1, GlobalValueClass.GET_FileName().toString());
	        }    

	        FileToSave = new File(dir1, GlobalValueClass.GET_FileName().toString().toString());
        }
		
		 try { out = new FileOutputStream (FileToSave,true);
	        } catch (FileNotFoundException e) { e.printStackTrace();}
	       
	        sb1.append("year,month,day,hour,minute,second,latitude,longitude,altitude,speed,vehicle,frequency\n");
	        
	        try {out.write(sb1.toString().getBytes());
			} catch (IOException e){
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		do{
			Log.d("######%$/","&&&&&&&&&&&&&&&&&&  1"+ GlobalValueClass.GetTrackingType());
			//Thread Sleeping
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	        if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //JUST IN CASE
	        	
	        	longitude = MyLocationListener.Longitude;
	        	latitude = MyLocationListener.Latitude;
	        	altitude = MyLocationListener.Altitude;
	        	speed = MyLocationListener.Speed;
	        	
	        	
	        	
	            if(latitude != 0 && longitude != 0) 
	            {  
	            	//WRITE TO CSV FILE
	            	calendar = Calendar.getInstance();
	            	 sb1 = new StringBuilder();  
	            	 sb1.append(calendar.get(Calendar.YEAR)+","
	            			 +(int)(calendar.get(Calendar.MONTH)+1)+","
	            			 +calendar.get(Calendar.DAY_OF_MONTH)+","
	            			 +calendar.get(Calendar.HOUR_OF_DAY)+","
	            			 +calendar.get(Calendar.MINUTE)+","
	            			 +calendar.get(Calendar.SECOND)+","
	            			 +latitude+","
	            			 +longitude+","
	            			 +altitude+","
	            			 +speed+","
	            			 +GlobalValueClass.GetTrackingType()+","
	            			 +GlobalValueClass.GET_Frequency()+",\n");
	            	 
	            	try {out.write(sb1.toString().getBytes());
	        		} catch (IOException e){
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
            	
	            	try {out.write(sb1.toString().getBytes());
	        		} catch (IOException e){
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}

	            	//TEMP--------------------------
	            	String s = new String();
	            	s+= "   latitude=  "+latitude +"   longitude=  "
	            			+ longitude+"   Altitude=  "+altitude+"   speed=  "+speed + "  vehicle="
	            			+GlobalValueClass.GetTrackingType() + "  Frequency=  "+GlobalValueClass.GET_Frequency();
	            	
	           	 	Progress[0] = s;
	           	 	publishProgress(Progress);
	           	 	//------------------------------
	           	 	
	            } 
	            /*
	            else{

	            	//TEMP--------------------------
	            	 calendar = Calendar.getInstance();
	            	 sb1 = new StringBuilder();  
	            	 sb1.append(calendar.get(Calendar.YEAR)+","
	            			 +(int)(calendar.get(Calendar.MONTH)+1)+","
	            			 +calendar.get(Calendar.DAY_OF_MONTH)+","
	            			 +calendar.get(Calendar.HOUR_OF_DAY)+","
	            			 +calendar.get(Calendar.MINUTE)+","
	            			 +calendar.get(Calendar.SECOND)+","
	            			 +latitude+","
	            			 +longitude+","
	            			 +altitude+","
	            			 +speed+",\n");
	            	//------------------------------
	            
		            	try {out.write(sb1.toString().getBytes());
		        		} catch (IOException e){
		        			// TODO Auto-generated catch block
		        			e.printStackTrace();
		        		}

	            	 //LOGGING
	            	 String s = new String();
	            	 s+= "   latitude=  "+latitude +"   longitude=  "
	     	            	+ longitude+"   Altitude=  "+altitude+"   speed=  "+speed;
	            	 
	            	 Progress[0] = s;
	            	 publishProgress(Progress);
	             }*/
	          } 
	        else {
	        	  String s = new String();
	              s+="GPS is not turned on...";  
	              Progress[0] = s;
	              publishProgress(Progress);
	          }  
		}while(GEttingCoordinates);
		
		try {out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	protected void onProgressUpdate(String... values) 
	{
		super.onProgressUpdate(values); //update the context
		Toast toast = Toast.makeText(UIThread, values[0].toString(), 200);
		//toast.show();
	}
	
	public void SetKeepTracking(boolean Flag){GEttingCoordinates = Flag;}
	
}
